import string

from django.http import HttpResponse
from django.shortcuts import render,redirect,reverse
from django.contrib import messages
from app1.models import LoginUser
from PIL import Image,ImageDraw,ImageFont
import re
import string
import random
import io

# 登錄校驗新加的
def login(request):
    if request.method=='GET':
        return render(request,'login/login.html')
    loginname = request.POST.get('loginname')
    if loginname is None:
        return render(request,'login/login.html')
    loginpass = request.POST.get('loginpass')
    if loginpass is None:
        return render(request,'login/login.html')
    vericode = request.POST.get('vericode')
    if vericode is None:
        return render(request,'login/login.html')
    vericode_insession = request.session.get('vericode')
    if vericode_insession!=None and vericode_insession==vericode:
        c = LoginUser.objects.filter(loginname=loginname,loginpass=loginpass).count()
        if c==1:
            request.session['loginname'] = loginname
            return redirect(reverse('index'))
        else:
            messages.error(request,'用户名密码校验错误！')
    else:
        messages.error(request,'校验码错误！')
    return redirect(reverse('login'))
# 退出是新加的
def loginout(request):
    return redirect(reverse('login'))
# 這裏是新增的，注冊
def reg(request):
    if request.method=='GET':
        return render(request,'login/register.html')
    loginname = request.POST.get('loginname')
    loginpass = request.POST.get('loginpass')
    c = LoginUser.objects.filter(loginname=loginname,loginpass=loginpass).count()
    if c==0:
        # 添加用户
        LoginUser.objects.create(loginname=loginname, loginpass=loginpass)
        return redirect(reverse('login'))
    else:
        messages.error(request,'用户已存在！')

    return redirect(reverse('register'))

def getvericodeimg(request):
    vericode_text = re.sub(r'0|o|l|1','',string.digits+string.ascii_lowercase)
    vericode_text = "".join(random.choices(vericode_text,k=4))
    request.session['vericode'] = vericode_text

    img = Image.new('RGB',size=(80,21),color=(125,138,140))
    draw = ImageDraw.Draw(img)
    font = ImageFont.truetype('simhei.ttf',size=18)
    for idx,ch in enumerate(vericode_text):
        draw.text((idx*20+4,1),ch,font=font,fill=(0,0,0))

    buff = io.BytesIO()
    img.save(buff,format='PNG')

    resp = HttpResponse(buff.getvalue(),content_type="image/png")
    return resp

# 這裏是修改的跳轉到base.html
def index(request):
    return render(request,"base.html")